package com.sws.web.controller.ry_rongyue.customer;

import java.util.List;

import com.sws.customer.domain.RyCustomer;
import com.sws.customer.service.IRyCustomerService;
import com.sws.rel.service.IPersonDeviceRelService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sws.common.annotation.Log;
import com.sws.common.core.controller.BaseController;
import com.sws.common.core.domain.AjaxResult;
import com.sws.common.enums.BusinessType;

import com.sws.common.utils.poi.ExcelUtil;
import com.sws.common.core.page.TableDataInfo;

/**
 * 核心人员信息Controller
 * 
 * @author cx
 * @date 2025-06-23
 */
@RestController
@RequestMapping("/ry/customer/customer")
public class RyCustomerController extends BaseController
{
    @Autowired
    private IRyCustomerService ryCustomerService;
    
    @Autowired
    private IPersonDeviceRelService personDeviceRelService;

    /**
     * 查询核心人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('ry/customer:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(RyCustomer ryCustomer)
    {
        startPage();
        List<RyCustomer> list = ryCustomerService.selectRyCustomerList(ryCustomer);
        return getDataTable(list);
    }

    /**
     * 导出核心人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('ry/customer:customer:export')")
    @Log(title = "核心人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RyCustomer ryCustomer)
    {
        List<RyCustomer> list = ryCustomerService.selectRyCustomerList(ryCustomer);
        ExcelUtil<RyCustomer> util = new ExcelUtil<RyCustomer>(RyCustomer.class);
        util.exportExcel(response, list, "核心人员信息数据");
    }

    /**
     * 获取核心人员信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('ry/customer:customer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        RyCustomer customer = ryCustomerService.selectRyCustomerById(id);
        
        // 查询此顾客关联的所有设备
        if (customer.getPid() != null && !customer.getPid().isEmpty()) {
            List<String> deviceSns = personDeviceRelService.getDeviceSnsByPersonPid(customer.getPid());
            customer.setDeviceIds(deviceSns);
        }
        
        return success(customer);
    }

    /**
     * 新增核心人员信息
     */
    @PreAuthorize("@ss.hasPermi('ry/customer:customer:add')")
    @Log(title = "核心人员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RyCustomer ryCustomer)
    {
        // 检查设备ID列表是否提供
        if (ryCustomer.getDeviceIds() == null || ryCustomer.getDeviceIds().isEmpty()) {
            return error("请至少选择一个设备");
        }
        
        // 设置deviceSn为第一个设备ID（作为主设备）
        ryCustomer.setDeviceSn(ryCustomer.getDeviceIds().get(0));
        
        try {
            return toAjax(ryCustomerService.insertRyCustomer(ryCustomer));
        } catch (Exception e) {
            logger.error("添加客户失败", e);
            return AjaxResult.error("添加客户失败：" + e.getMessage());
        }
    }

    /**
     * 修改核心人员信息
     */
    @PreAuthorize("@ss.hasPermi('ry/customer:customer:edit')")
    @Log(title = "核心人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RyCustomer ryCustomer)
    {
        // 检查设备ID列表是否提供
        if (ryCustomer.getDeviceIds() == null || ryCustomer.getDeviceIds().isEmpty()) {
            return error("请至少选择一个设备");
        }
        
        // 设置deviceSn为第一个设备ID（作为主设备）
        ryCustomer.setDeviceSn(ryCustomer.getDeviceIds().get(0));
        
        try {
            return toAjax(ryCustomerService.updateRyCustomer(ryCustomer));
        } catch (Exception e) {
            logger.error("修改客户失败", e);
            return AjaxResult.error("修改客户失败：" + e.getMessage());
        }
    }

    /**
     * 删除核心人员信息
     */
    @PreAuthorize("@ss.hasPermi('ry/customer:customer:remove')")
    @Log(title = "核心人员信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ryCustomerService.deleteRyCustomerByIds(ids));
    }
} 